<template>
  <div class="transaction-history">
    <h2>收支明细</h2>
    <div class="search-bar">
      <input 
        type="text" 
        v-model="searchQuery" 
        placeholder="搜索..." 
        @input="debounceSearch"
      />
      <button v-if="searchQuery" @click="clearSearch" title="清除搜索">X</button>
    </div>
    <p v-if="!filteredTransactions.length && searchQuery" class="no-results">没有找到相关记录。</p>
    <ul v-else>
      <li v-for="(transaction, index) in filteredTransactions" :key="index">
        {{ transaction.date }} - {{ transaction.description }} - ¥{{ transaction.amount }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'TransactionHistory',
  data() {
    return {
      transactions: [
        { date: '2024-12-19', description: '工资收入', amount: 18000.00 },
        { date: '2024-12-17', description: '购物支出', amount: -200.00 },
        { date: '2024-11-19', description: '工资收入', amount: 18000.00 },
        { date: '2024-11-16', description: '购物支出', amount: -1200.00 },
        { date: '2024-10-19', description: '工资收入', amount: 18000.00 },
        { date: '2024-10-17', description: '购物支出', amount: -200.00 },
        { date: '2024-10-16', description: '购物支出', amount: -10.00 },
        { date: '2024-10-16', description: '购物支出', amount: -100.00 },
        // 添加更多交易记录...
      ],
      searchQuery: '',
      debounceTimer: null,
    };
  },
  computed: {
    filteredTransactions() {
      const query = this.searchQuery.toLowerCase();
      if (!query) return this.transactions;

      return this.transactions.filter((transaction) => {
        return (
          transaction.description.toLowerCase().includes(query) ||
          transaction.date.includes(query) || // 支持按日期搜索
          transaction.amount.toString().includes(query) // 支持按金额搜索
        );
      });
    },
  },
  methods: {
    debounceSearch() {
      clearTimeout(this.debounceTimer);
      this.debounceTimer = setTimeout(() => {
        // 这里可以调用任何你想要的搜索逻辑
      }, 300); // 设置延迟时间为300ms
    },
    clearSearch() {
      this.searchQuery = '';
      this.$nextTick(() => {
        this.$el.querySelector('input').focus(); // 搜索框自动获取焦点
      });
    }
  }
};
</script>

<style scoped>
.transaction-history {
  font-family: Arial, sans-serif;
}

.search-bar {
  position: relative;
  width: 100%;
}

.search-bar input {
  width: 100%;
  padding: 8px;
  margin-bottom: 10px;
}

.search-bar button {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
}

.no-results {
  color: #999;
  text-align: center;
}

.transaction-history ul {
  list-style-type: none;
  padding: 0;
}

.transaction-history li {
  padding: 5px 0;
  border-bottom: 1px solid #ccc;
}
</style>